<?php

namespace app\controller\admin;

use Curl\Curl;
use think\facade\View;
use geetest\GeetestLib;
use think\Request;
use think\exception\ValidateException;

class Login
{
    public function index(Request $req)
    {
        if ($req->isPost()) {
            $check = $req->checkToken();
            if (false === $check) {
                throw new ValidateException('invalid token');
            }

            //进行极验二次验证
            if (!$this->gt_validate()) {
                return '验证失败';
            }

            return '验证通过';
        }

        return View::fetch();
    }

    public function gt_register(Request $req)
    {
        $gt_public_key = C("gt_public_key");
        $gt_private_key = C("gt_private_key");

        $param = [
            'user_id' => 'test',
            'client_type' => $req->isMobile() ? 'h5' : 'web',
            'ip_address' => $req->ip(),
            'gt' => $gt_public_key,
            'new_captcha' => 1
        ];

        //获取极验第一次请求返回的md5校验码
        $query = http_build_query($param);
        $url = "https://api.geetest.com/register.php?" . $query;

        $curl = new Curl();
        $curl->get($url);

        //没有宕机模式
        $challenge = md5($curl->response . $gt_private_key);
        $data = [
            'success' => 1,
            'gt' => $gt_public_key,
            'challenge' => $challenge,
            'new_captcha' => 1
        ];

        return json($data);
    }

    public function gt_validate()
    {
        $req = request();
        $geetest_challenge = $req->post('geetest_challenge');
        $geetest_validate = $req->post('geetest_validate');
        $geetest_seccode = $req->post('geetest_seccode');

        $param = [
            "seccode" => $geetest_seccode,
            "timestamp" => time(),
            "challenge" => $geetest_challenge,
            "captchaid" => C("gt_public_key"),
            "json_format" => 1,
            "sdk" => 'php_3.0.0',
            "user_id" => 'test',
            "client_type" => $req->isMobile() ? 'h5' : 'web',
            "ip_address" => $req->ip()
        ];

        $url = "https://api.geetest.com/validate.php";

        $curl = new Curl();
        $curl->post($url, $param);

        $obj = json_decode($curl->response, true);
        if ($obj && $obj['seccode'] == md5($geetest_seccode)) {
            return true;
        } else {
            return false;
        }
    }
}
